package sk.muf.mufpong;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.view.MotionEvent;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

public class MainView extends View {
    Game game;
    Timer timer;
    int height = 0;

    public MainView(Context context) {
        super(context);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (game == null) {
            height = h;
            game = new Game(w, h);
            startTimer();
        }
    }

    private void startTimer() {
        timer = new Timer();
        final Handler tickHandler = new Handler();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                tickHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        game.step();
                        invalidate();
                    }
                });
            }
        };
        timer.schedule(timerTask, game.getTimeInterval(), game.getTimeInterval());
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        game.drawMyself(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        int count = event.getPointerCount();
        for (int i = 0; i < count; i++) {
            int y = (int) MotionEventCompat.getY(event, i);
            if (y > height / 2) {
                game.setMyPosition((int) MotionEventCompat.getX(event, i));
            } else {
                game.setHisPosition((int) MotionEventCompat.getX(event, i));
            }
        }

        invalidate();
        return true;
    }

    public void onPause() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }
    }

    public void onResume() {
        if (game != null) startTimer();
    }
}